{% extends "secretariat_base.html" %}

{% block headblock %}
	<script src="{{ MEDIA_URL }}/js/jquery.dataTables.min.js" type="text/javascript" charset="utf-8"></script>	
	<script src="{{ MEDIA_URL }}/js/dataTables.fnAddTr.js" type="text/javascript" charset="utf-8"></script>
	<script src="{{ MEDIA_URL }}/js/jquery.jeditable.mini.js" type="text/javascript" charset="utf-8"></script>
	<script src="{{ MEDIA_URL }}/js/jquery.metadata.js" type="text/javascript" charset="utf-8"></script>
	<script src="{{ MEDIA_URL }}/js/autoNumeric-1.6.2.js" type="text/javascript" charset="utf-8"></script>
{% endblock %}

{% block scriptblock %}
var committeeTable;
var countryTable;
var paymentTable;
var feeTable;
var datepenaltyTable;

function form_cleanup() {
	$('input#id_date').datepicker();
	$('input#id_start_date').datepicker();
	$('input#id_end_date').datepicker();
	$('input#id_late_registration_start_date').datepicker();
	$('input#id_late_delegate_registration_start_date').datepicker();
	$('input#id_no_refunds_start_date').datepicker();
	$('input.auto').each(function() {
		$(this).autoNumeric();
		$(this).val($.fn.autoNumeric.Format($(this).attr("id"), $(this).val()));
	});
	
	form_styling();
}

function form_committee_row(committee) {
	var name;
	if(typeof( committee.fields ) != "undefined")
		name = committee.fields.name;
	else
		name = committee.name;

	row_html = "<tr pk=\"" + committee.pk + "\">";
	row_html += "<td class=\"name\" id=\"name_" + committee.pk + "\">" + name + "</td>";
	row_html += "<td class=\"delete\" id=\"" + committee.pk + "\"><a href=\"delete-committee\" id=\"delete_committee\" title=\"Delete\"><span class=\"ui-icon ui-icon-closethick\"></span></a></td></tr>";
	return row_html;
}

function form_country_row(country) {
	name = country.fields.name;
	country_code = country.fields.country_code.toLowerCase();

	row_html = "<tr pk=\"" + country.pk + "\">";
	row_html += "<td class=\"icon\" id=\"icon_" + country.pk + "\">";
	if(country_code.length > 0)
		row_html += "<img src=\"{{ MEDIA_URL }}/icons/country_flags/flag-" + country_code + ".png\" />";
	row_html += "</td><td class=\"name\" id=\"name_" + country.pk + "\">" + name + "</td>";
	row_html += "<td class=\"delete\" id=\"" + country.pk + "\"><a href=\"delete-country\" id=\"delete_country\" title=\"Delete\"><span class=\"ui-icon ui-icon-closethick\"></span></a></td></tr>";
	return row_html;
}

function form_payment_row(payment) {
	// ['School','Payment Type','Date Received','Amount','Notes','Delete']
	row_html = "<tr pk=\"" + payment.pk + "\">";
	row_html += "<td class=\"school\" id=\"school_" + payment.pk + "\">" + payment.fields.school + "</td>";
	row_html += "<td class=\"type\" id=\"type_" + payment.pk + "\">" + payment.fields.type + "</td>";
	row_html += "<td class=\"date\" id=\"date_" + payment.pk + "\">" + payment.fields.date + "</td>";
	row_html += "<td class=\"amount\" id=\"amount_" + payment.pk + "\">" + payment.fields.amount + "</td>";
	row_html += "<td class=\"notes\" id=\"notes_" + payment.pk + "\">" + payment.fields.notes + "</td>";
	row_html += "<td class=\"delete\" id=\"" + payment.pk + "\"><a href=\"delete-payment\" id=\"delete_payment\" title=\"Delete\"><span class=\"ui-icon ui-icon-closethick\"></span></a></td></tr>";
	return row_html;
}

function form_fee_row(fee) {
	row_html = "<tr pk=\"" + fee.pk + "\">";
	row_html += "<td class=\"name\" id=\"name_" + fee.pk + "\">" + fee.fields.name + "</td>";
	row_html += "<td class=\"amount\" id=\"amount_" + fee.pk + "\">" + fee.fields.amount + "</td>";
	row_html += "<td class=\"per\" id=\"per_" + fee.pk + "\">" + fee.fields.per + "</td>";
	row_html += "<td class=\"delete\" id=\"" + fee.pk + "\"><a href=\"delete-fee\" id=\"delete_fee\" title=\"Delete\"><span class=\"ui-icon ui-icon-closethick\"></span></a></td></tr>";
	return row_html;
}

function form_datepenalty_row(fee) {
	row_html = "<tr pk=\"" + fee.pk + "\">";
	row_html += "<td class=\"name\" id=\"name_" + fee.pk + "\">" + fee.fields.name + "</td>";
	row_html += "<td class=\"amount\" id=\"amount_" + fee.pk + "\">" + fee.fields.amount + "</td>";
	row_html += "<td class=\"per\" id=\"per_" + fee.pk + "\">" + fee.fields.per + "</td>";
	row_html += "<td class=\"based_on\" id=\"based_on_" + fee.pk + "\">" + fee.fields.based_on + "</td>";
	row_html += "<td class=\"start_date\" id=\"start_date_" + fee.pk + "\">" + fee.fields.start_date + "</td>";
	row_html += "<td class=\"end_date\" id=\"end_date_" + fee.pk + "\">" + fee.fields.end_date + "</td>";
	row_html += "<td class=\"delete\" id=\"" + fee.pk + "\"><a href=\"delete-datepenalty\" id=\"delete_datepenalty\" title=\"Delete\"><span class=\"ui-icon ui-icon-closethick\"></span></a></td></tr>";
	return row_html;
}

function formset_click_handler(object_name, data_table) {
	$('a#delete_'+object_name).unbind("click").click(function(event) {
		$.post(
			'ajax/remove-'+object_name,
			{'pk': $(event.target.parentNode.parentNode).attr("id")},
			function(data) {
				var aTrs = data_table.fnGetNodes();
				for ( var i=0 ; i<aTrs.length ; i++ )
				{
					if ( $(aTrs[i]).attr('pk') == data.pk )
					{
						data_table.fnDeleteRow( aTrs[i] );
						break;
					}
				}
			},
			'json'
		);
		return false;
	});	
}

function formset_row_handlers(object_name, data_table) {
    
	if(object_name != 'fee' && object_name.indexOf("penalty") == -1) {
		/* Apply the jEditable handlers to the table */
		$('td.name', data_table.fnGetNodes()).unbind("editable").editable( 'ajax/edit-'+object_name, {
			"callback": function( sValue, y ) {
				var aPos = data_table.fnGetPosition( this );
				data_table.fnUpdate( sValue, aPos[0], aPos[1], false );
			},
			"submitdata": function ( value, settings ) {
				return { "row_id": this.parentNode.getAttribute('id') };
			},
			"height": "25px",
			"tooltip" : 'Click to edit'
		} );
	}
		
	data_table.fnAdjustColumnSizing();
}

function get_formset_callback(data, table_headers, column_settings, column_sorting, data_table, object_name, dialog_element, form_element, row_renderer) {
	output = ""
	if(object_name == 'fee')
		output += "<p>Enter all fees to charge schools.</p>"
	else if(object_name == 'datepenalty')
		output += "<p>Enter all penalties and discounts to charge schools based on an action during a date range. For example, charge a $5 penalty per delegate if the school registers late. Enter discounts as a negative penalty (aka -$5.00).</p>"
	else if(object_name != "payment")
    	output += "<p>Click on any " + object_name + " to edit it; press Enter to save your changes.</p>";
    output += "<table class=\"datatable\" id=\"existing_" + object_name + "\"><thead><tr>";
    for(i = 0; i < table_headers.length; i++) {
    	output += "<th>" + table_headers[i] + "</th>";
    }
    output += "</tr></thead><tbody>";
    
    parsed_objects = jQuery.parseJSON(data.objects);
    for (i = 0; i < parsed_objects.length; i++) {
        output += row_renderer(parsed_objects[i]);
    }
    output += "</tbody></table>";
    
    output += "<form action=\"ajax/add-"+object_name+"\" method=\"post\" id=\"" + form_element.replace('#','') + "\">";
    output += data.form;
    output += "<input value=\"Add\" type=\"submit\" id=\"add_" + object_name + "\">";
    output += "</form>";
	
    $('.loading').remove();
    $(dialog_element).html(output);
    $("input:submit").button();
    form_cleanup();
    
    $(form_element).ajaxForm({ 
    	dataType:	'json',
    	beforeSerialize:	function($form, options) { 
	    	$('input.auto').each(function() {
				$(this).val($.fn.autoNumeric.Strip($(this).attr("id"), $(this).val()));
			}); 
    	},
        success:   function(return_data) {
			if(return_data != null && return_data.form != null) {
	  			// re-load form with errors
				decoded = return_data.form;
		        $(form_element).html(decoded);
	  			$(form_element).append("<input value=\"Add\" type=\"submit\" id=\"add_" + object_name + "\">");
	  		    $("input:submit").button();
	  		    form_cleanup();
			} else {
				// add the new object to the table
				$(form_element).resetForm();
				var row = row_renderer(return_data);
				data_table.fnAddTr( $(row)[0] );
				formset_row_handlers(object_name, data_table);
			}
		}
    });
    
	data_table = $('table#existing_'+object_name).dataTable({
		"bJQueryUI": true,
		"sPaginationType": "full_numbers",
		"aoColumns": column_settings,
		"aaSorting": column_sorting,
		"fnDrawCallback": function(){
			formset_click_handler(object_name, this);
	     	$('td','table#existing_'+object_name).bind('mouseenter', function () { $(this).parent().children().each(function(){ $(this).addClass('datatablerowhighlight'); }); });
	     	$('td','table#existing_'+object_name).bind('mouseleave', function () { $(this).parent().children().each(function(){$(this).removeClass('datatablerowhighlight');}); });
		}
	});
	
	formset_row_handlers(object_name, data_table);
}

function isNumeric(value) {
	if (value == null || !value.toString().match(/^[-]?\d*\.?\d*$/)) return false;
	return true;
}

function gen_uuid() {
    var uuid = ""
    for (var i=0; i < 32; i++) {
        uuid += Math.floor(Math.random() * 16).toString(16); 
    }
    return uuid
}

function get_delegate_positions_callback(data, dialog_element) {
    output = "<p>Click on any number to edit the number of delegates represented by that country on that committee. Press Enter to save your changes.</p>";
    
    // table headers
    output += "<table class=\"datatable\" id=\"delegate_positions\">";
    output += data.table;
    output += "</table>";
    
    $('.loading').remove();
    $('#positions-assignment-table').html(output);
    
	data_table = $('table#delegate_positions').dataTable({
		"bJQueryUI": true,
		"sPaginationType": "full_numbers",
		"fnDrawCallback": function(){
	     	$('td','table#delegate_positions').bind('mouseenter', function () { $(this).parent().children().each(function(){ $(this).addClass('datatablerowhighlight'); }); });
	     	$('td','table#delegate_positions').bind('mouseleave', function () { $(this).parent().children().each(function(){$(this).removeClass('datatablerowhighlight');}); });
		}
	});
	
	/* Apply the jEditable handlers to the table */
	$('td.position_count', data_table.fnGetNodes()).editable( 'ajax/set-delegate-positions', {
		"onsubmit": function(settings, td) {
	    	var input = $(td).find('input');
	        var original = input.val();
	        if (isNumeric(original)) {
	            return true;
	        } else {
	            input.css('background-color','#c00').css('color','#fff');
	            return false;
	        }
	    },
		"callback": function( sValue, y ) {
			var aPos = data_table.fnGetPosition( this );
			data_table.fnUpdate( sValue, aPos[0], aPos[1], false );
		},
		"submitdata": function ( value, settings ) {
			return { "row_id": this.parentNode.getAttribute('id') };
		},
		"height": "25px",
		"tooltip" : 'Click to edit'
	} );
	
	data_table.fnAdjustColumnSizing();
}

function get_school_country_assignments_callback(data, selectSource, dialog_element) {
    output = "<p>Click in the School column to change the school assigned to that country.</p>";
    
    // table headers
    output += "<table class=\"datatable\" id=\"school_country_assignments\">";
    output += data.table;
    output += "</table>";
    
    $('.loading').remove();
    $('#school-country-assignment-table').html(output);
    
	data_table = $('table#school_country_assignments').dataTable({
		"bJQueryUI": true,
		"sPaginationType": "full_numbers",
		"fnDrawCallback": function(){
	     	$('td','table#school_country_assignments').bind('mouseenter', function () { $(this).parent().children().each(function(){ $(this).addClass('datatablerowhighlight'); }); });
	     	$('td','table#school_country_assignments').bind('mouseleave', function () { $(this).parent().children().each(function(){$(this).removeClass('datatablerowhighlight');}); });
		}
	});
	
	/* Apply the jEditable handlers to the table */
	$('td.school_assignment', data_table.fnGetNodes()).editable( 'ajax/set-country-school-assignments', {
		data   : selectSource,
	    type   : 'select',
	    submit : 'OK',
	    placeholder: "Click to assign school", 
		"callback": function( sValue, y ) {
			var aPos = data_table.fnGetPosition( this );
			data_table.fnUpdate( sValue, aPos[0], aPos[1], false );
		},
		"submitdata": function ( value, settings ) {
			return { "row_id": this.parentNode.getAttribute('id') };
		},
		"height": "25px",
		"tooltip" : 'Click to edit'
	} );
	
	data_table.fnAdjustColumnSizing();
}

function individual_delegate_positions_row_handlers(data_table, schoolSelectSource, countrySelectSource, committeeSelectSource) {
	/* Apply the jEditable handlers to the table */
	$('td.delegate_position_country', data_table.fnGetNodes()).unbind("editable").editable( 'ajax/set-individual-delegate-positions', {
		data   : countrySelectSource,
	    type   : 'select',
	    submit : 'OK',
	    placeholder: "Click to assign country", 
		"callback": function( sValue, y ) {
			var aPos = data_table.fnGetPosition( this );
			data_table.fnUpdate( sValue, aPos[0], aPos[1], false );
		},
		"submitdata": function ( value, settings ) {
			return { "row_class": this.getAttribute('class') };
		},
		"height": "25px",
		"tooltip" : 'Click to edit'
	} );
	$('td.delegate_position_committee', data_table.fnGetNodes()).unbind("editable").editable( 'ajax/set-individual-delegate-positions', {
		data   : committeeSelectSource,
	    type   : 'select',
	    submit : 'OK',
	    placeholder: "Click to assign committee", 
		"callback": function( sValue, y ) {
			var aPos = data_table.fnGetPosition( this );
			data_table.fnUpdate( sValue, aPos[0], aPos[1], false );
		},
		"submitdata": function ( value, settings ) {
			return { "row_class": this.getAttribute('class') };
		},
		"height": "25px",
		"tooltip" : 'Click to edit'
	} );
	$('td.delegate_position_school', data_table.fnGetNodes()).unbind("editable").editable( 'ajax/set-individual-delegate-positions', {
		data   : schoolSelectSource,
	    type   : 'select',
	    submit : 'OK',
	    placeholder: "Click to assign school", 
		"callback": function( sValue, y ) {
			var aPos = data_table.fnGetPosition( this );
			data_table.fnUpdate( sValue, aPos[0], aPos[1], false );
		},
		"submitdata": function ( value, settings ) {
			return { "row_class": this.getAttribute('class') };
		},
		"height": "25px",
		"tooltip" : 'Click to edit'
	} );
	$('td.delegate_position_title', data_table.fnGetNodes()).unbind("editable").editable( 'ajax/set-individual-delegate-positions', {
		"callback": function( sValue, y ) {
			var aPos = data_table.fnGetPosition( this );
			data_table.fnUpdate( sValue, aPos[0], aPos[1], false );
		},
		"submitdata": function ( value, settings ) {
			return { "row_class": this.getAttribute('class') };
		},
		"height": "25px",
		"tooltip" : 'Click to edit'
	} );
    		
	data_table.fnAdjustColumnSizing();	
}

function delete_delegate_positions_handler(data_table) {
	$('a#delete_delegate_position').unbind("click").click(function(event) {
		$.post(
			'ajax/remove-delegate-position',
			{'id': $(event.target.parentNode.parentNode).attr("id")},
			function(data) {
				var aTrs = data_table.fnGetNodes();
				for ( var i=0 ; i<aTrs.length ; i++ )
				{
					if ( $(aTrs[i]).attr('id') == data.id )
					{
						data_table.fnDeleteRow( aTrs[i] );
						break;
					}
				}
			},
			'json'
		);
		return false;
	});	
}

function get_individual_delegate_positions_callback(data, schoolSelectSource, countrySelectSource, committeeSelectSource, dialog_element) {
    output = "<p>Edit individual delegate positions by clicking in any column. To edit a delegate's title, press Enter after entering the new title.</p>";
    
    // table headers
    output += "<table class=\"datatable\" id=\"delegate_positions\">";
    output += data.table;
    output += "</table>";
    
    output += "<form action=\"ajax/add-delegate-position\" method=\"post\" id=\"new_delegate_position_form\">";
    output += data.form;
    output += "<input value=\"Add\" type=\"submit\" id=\"add-delegate-position\"></form>";
    
    $('.loading').remove();
    $('#delegate-positions-table').html(output);
    $("input:submit").button();
    form_cleanup();
    
    column_settings = [ 
   			/* Country */  	null,
   			/* Committee */ null,
   			/* School */  	null,
   			/* Title */  	null,
			/* Delete */ 	{ "bSearchable": false, "bSortable": false }
		];
    
	data_table = $('table#delegate_positions').dataTable({
		"bJQueryUI": true,
		"aoColumns": column_settings,
		"sPaginationType": "full_numbers",
		"fnDrawCallback": function(){
			delete_delegate_positions_handler(this);
	     	$('td','table#delegate_positions').bind('mouseenter', function () { $(this).parent().children().each(function(){ $(this).addClass('datatablerowhighlight'); }); });
	     	$('td','table#delegate_positions').bind('mouseleave', function () { $(this).parent().children().each(function(){$(this).removeClass('datatablerowhighlight');}); });
		}
	});
	
	individual_delegate_positions_row_handlers(data_table, schoolSelectSource, countrySelectSource, committeeSelectSource);
	
	$("#new_delegate_position_form").ajaxForm({ 
    	dataType:	'json',
        success:   function(return_data) {
			if(return_data != null && return_data.form != null) {
	  			// re-load form with errors
				decoded = return_data.form;
		        $("#new_delegate_position_form").html(decoded);
	  			$("#new_delegate_position_form").append("<input value=\"Add\" type=\"submit\" id=\"add-delegate-position\">");
	  		    $("input:submit").button();
	  		    form_cleanup();
			} else {
				// add the new object to the table
				$("#new_delegate_position_form").resetForm();
				var row = return_data.row;
				data_table.fnAddTr( $(row)[0] );
				individual_delegate_positions_row_handlers(data_table, schoolSelectSource, countrySelectSource, committeeSelectSource);
			}
		}
    });
}

function form_dialog(dialog_width, dialog_element, dialog_link_element, form_element, ajax_get_url) {
	$(dialog_element).dialog({
		autoOpen: false,
		width: dialog_width,
		modal: true,
		resizable: false,
		position: 'top',
		close: function(event, ui) {
			$(dialog_element).html("");
		},
		buttons: {
			"Save": function() {
				$('input.auto').each(function() {
					$(this).val($.fn.autoNumeric.Strip($(this).attr("id"), $(this).val()));
				});

		 		$(form_element).ajaxSubmit({
		 			dataType:	'json',
		 			success:	function(data) {
						if(data != null && data.form != null) {
				  			// re-load form with errors
				  			$(form_element).html(data.form);
				  			form_cleanup();
						} else {
							$(dialog_element).dialog("close");
						}
					}
		 		}); 
			},
			"Cancel": function() {
				$(this).dialog("close");
			}
		}
	});
		  
	$(dialog_link_element).click(function(){
		$.get(
			"ajax/" + ajax_get_url,
			function(data) {
				$('.loading').remove();
	  			$(dialog_element).html(data.form);
	  			form_cleanup();
			},
			"json"
		);
	
		$(dialog_element).append('<p style="text-align: center" class="loading"><img src="{{MEDIA_URL}}/icons/ajax-loader.gif"/><br/><br/>Loading...</p>');
		$(dialog_element).dialog('open');
		return false;
	});
}

function formset_dialog(dialog_width, dialog_element, dialog_link_element, form_element, ajax_get_url, table_headers, column_settings, column_sorting, data_table, object_name, row_renderer) {
	$(dialog_element).dialog({
		autoOpen: false,
		width: dialog_width,
		modal: true,
		resizable: false,
		position: 'top',
		close: function(event, ui) {
			$(dialog_element).html("");
		},
		buttons: {
			"Close": function() {
				$(this).dialog("close");
			}
		}
	});
		  
	$(dialog_link_element).click(function(){
		$.get(
			"ajax/" + ajax_get_url,
			function(data) {
				if(get_formset_callback != undefined)
					get_formset_callback(data, table_headers, column_settings, column_sorting, data_table, object_name, dialog_element, form_element, row_renderer);
			},
			"json"
		);
	
		$(dialog_element).append('<p style="text-align: center" class="loading"><img src="{{MEDIA_URL}}/icons/ajax-loader.gif"/><br/><br/>Loading...</p>');
		$(dialog_element).dialog('open');
		return false;
	});
}

var progressTimer;
$(function(){
	form_dialog(500, '#basic-conference-form-dialog', '#basic-conference-form-dialog-link', '#basic_conference_info_form', "get-basic-conference-form");

	committeeHeaders = ['Name','Delete'];
	committeeColumnSettings = [ 
	               			/* Name */  	null,
	            			/* Delete */ 	{ "bSearchable": false, "bSortable": false }
	            		];
	committeeColumnSorting = [[ 0, "asc" ]]
	formset_dialog(900, '#committees-form-dialog', '#committees-form-dialog-link', '#new_conference_committees_form',
		"get-conference-committees", committeeHeaders, committeeColumnSettings, committeeColumnSorting, committeeTable, 'committee', form_committee_row);

	countryHeaders = ['Flag','Name','Delete'];
	countryColumnSettings = [ 
	             			/* Icon */  	{ "bSearchable": false, "bSortable": false },
	            			/* Name */  	null,
	            			/* Delete */ 	{ "bSearchable": false, "bSortable": false }
	            		];
	countryColumnSorting = [[ 1, "asc" ]]
	formset_dialog(900, '#countries-form-dialog', '#countries-form-dialog-link', '#new_conference_countries_form',
		"get-conference-countries", countryHeaders, countryColumnSettings, countryColumnSorting, countryTable, 'country', form_country_row);

	paymentHeaders = ['School','Payment Type','Date Received','Amount','Notes','Delete'];
	paymentColumnSettings = [ 
	             			/* School */  	null,
	            			/* Type */  	{ "bSearchable": false },
	            			/* Date */  	{ "bSearchable": false },
	            			/* Amount */  	{ "bSearchable": false },
	            			/* Notes */  	null,
	            			/* Delete */ 	{ "bSearchable": false, "bSortable": false }
	            		];
	paymentColumnSorting = [[ 2, "desc" ]]
	formset_dialog(900, '#payments-form-dialog', '#payments-form-dialog-link', '#new_conference_payments_form',
		"get-conference-payments", paymentHeaders, paymentColumnSettings, paymentColumnSorting, paymentTable, 'payment', form_payment_row);

	var schoolSelectSource = "{ '-1':' ', {% for school in object.school_set.all %} \
		'{{ school.pk }}':'{{ school.name }}', \
	{% endfor %} }";
	var countrySelectSource = "{ {% for country in object.country_set.all %} \
		'{{ country.pk }}':'{{ country.name }}', \
	{% endfor %} }";
	var committeeSelectSource = "{ {% for committee in object.committee_set.all %} \
		'{{ committee.pk }}':'{{ committee.name }}', \
	{% endfor %} }";
 	
	var availableSchools = [{% for school in object.school_set.all %}
				"{{ school.name }}", 
			{% endfor %}];
	$(".search-schools input#id_name").autocomplete({
		source: availableSchools
	});
	
	feeHeaders = ['Name','Amount','Per','Delete'];
	feeSettings = [ 
	               			/* Name */  	null,
	               			/* Amount */  	null,
	               			/* Per */  	null,
	            			/* Delete */ 	{ "bSearchable": false, "bSortable": false }
	            		];
	feeColumnSorting = [[ 0, "asc" ]];
	formset_dialog(900, '#fee-form-dialog', '#fee-form-dialog-link', '#new_fee_form',
			"get-conference-fees", feeHeaders, feeSettings, feeColumnSorting, feeTable, 'fee', form_fee_row);

	datepenaltyHeaders = ['Name','Amount','Per','Based On','Start Date','End Date','Delete'];
	datepenaltySettings = [ 
	               			/* Name */  	null,
	               			/* Amount */  	null,
	               			/* Per */  	null,
	               			/* Based On */  	null,
	               			/* Start Date */  	null,
	               			/* End Date */  	null,
	            			/* Delete */ 	{ "bSearchable": false, "bSortable": false }
	            		];
	datepenaltyColumnSorting = [[ 0, "asc" ]];
	formset_dialog(900, '#datepenalty-form-dialog', '#datepenalty-form-dialog-link', '#new_datepenalty_form',
			"get-conference-datepenalties", datepenaltyHeaders, datepenaltySettings, datepenaltyColumnSorting, datepenaltyTable, 'datepenalty', form_datepenalty_row);

	$('#committees-to-countries-form-dialog').dialog({
		autoOpen: false,
		width: 900,
		modal: true,
		resizable: false,
		position: 'top',
		close: function(event, ui) {
			$('#positions-assignment-table').html("");
		},
		buttons: {
			"Close": function() {
				$(this).dialog("close");
			}
		}
	});
	
	$('#committees-to-countries-form-dialog-link').click(function(){
		$.get(
			"ajax/get-delegate-positions",
			function(data) {
				get_delegate_positions_callback(data, '#committees-to-countries-form-dialog', '#committees-to-countries-form');
			},
			"json"
		);
	
		$('#committees-to-countries-form-dialog').append('<p style="text-align: center" class="loading"><img src="{{MEDIA_URL}}/icons/ajax-loader.gif"/><br/><br/>Loading...</p>');
		$('#committees-to-countries-form-dialog').dialog('open');
		return false;
	});
	
    $('form#upload-delegate-positions-form').ajaxForm({ 
    	dataType:	'json',
    	beforeSubmit: function(formData, form, options) {
    		if ($.data(form, 'submitted')) return false;
	
	        var freq = 1000; // freqency of update in ms
	        var uuid = gen_uuid(); // id for this upload so we can fetch progress info.
	        var progress_url = '/upload-progress/'; // ajax view serving progress info
	
	        // Append X-Progress-ID uuid to form data
	        formData.push({ "name": "X-Progress-ID", "value": uuid });
	        
	        $('#upload-delegate-positions-progress').progressbar({ value: 0 });
	        
	        // Update progress bar
	        function update_progress_info() {
	            $.getJSON(progress_url, {'X-Progress-ID': uuid}, function(data, status){
	                if (data) {
	                    var progressPercent = parseInt(100*parseInt(data.uploaded) / parseInt(data.length));
	        	        $("#upload-delegate-positions-progress").progressbar("option", "value", progressPercent);

	                    if(progressPercent < 100)
	                    	progressTimer = window.setTimeout(update_progress_info, freq);
	                }
	            });
	        };
	        progressTimer = window.setTimeout(update_progress_info, freq);
	
	        $.data(form, 'submitted', true); // mark form as submitted.
	        return true;
    	},
        success:   function(return_data) {
    		window.clearTimeout(progressTimer);
    		$('#upload-delegate-positions-progress').progressbar("destroy");
    		$('div#upload-delegate-positions-form .ui-state-error').remove();
			if(return_data != null) {
				if(return_data.errors != null) {
		  			// show errors
					output = "<div style=\"padding: 0pt 0.7em;\" class=\"ui-state-error ui-corner-all\"> <p><span style=\"float: left; margin-right: 0.3em;\" class=\"ui-icon ui-icon-alert\"></span> ";
					for(i = 0; i < return_data.errors.length; i++) {
						output += return_data.errors[i] + "<br/>";
					}
					output += "</p></div>";
					
					$('div#upload-delegate-positions-form').append(output);
				}
				if(return_data.table != null) {
					// refresh the delegate positions table
					//return_data.table = $("<div/>").html(return_data.table).text();
					get_delegate_positions_callback(return_data, '#committees-to-countries-form-dialog', '#committees-to-countries-form');
				}
			}
		}
    });

	$('#countries-to-schools-form-dialog').dialog({
		autoOpen: false,
		width: 900,
		modal: true,
		resizable: false,
		position: 'top',
		close: function(event, ui) {
			$('#school-country-assignment-table').html("");
		},
		buttons: {
			"Close": function() {
				$(this).dialog("close");
			}
		}
	});
	
	$('#edit-delegate-positions-form-dialog').dialog({
		autoOpen: false,
		width: 900,
		modal: true,
		resizable: false,
		position: 'top',
		close: function(event, ui) {
			$('#delegate-positions-table').html("");
		},
		buttons: {
			"Close": function() {
				$(this).dialog("close");
			}
		}
	});
	
	$('#edit-delegate-positions-form-dialog-link').click(function(){
		$.get(
			"ajax/get-individual-delegate-positions",
			function(data) {
				get_individual_delegate_positions_callback(data, schoolSelectSource, countrySelectSource, committeeSelectSource, '#edit-delegate-positions-form-dialog');
			},
			"json"
		);
	
		$('#edit-delegate-positions-form-dialog').append('<p style="text-align: center" class="loading"><img src="{{MEDIA_URL}}/icons/ajax-loader.gif"/><br/><br/>Loading...</p>');
		$('#edit-delegate-positions-form-dialog').dialog('open');
		return false;
	});
					
	$('#countries-to-schools-form-dialog-link').click(function(){
		$.get(
			"ajax/get-country-school-assignments",
			function(data) {
				get_school_country_assignments_callback(data, schoolSelectSource, '#countries-to-schools-form-dialog');
			},
			"json"
		);
	
		$('#countries-to-schools-form-dialog').append('<p style="text-align: center" class="loading"><img src="{{MEDIA_URL}}/icons/ajax-loader.gif"/><br/><br/>Loading...</p>');
		$('#countries-to-schools-form-dialog').dialog('open');
		return false;
	});
					
    $('form#upload-school-country-assignments-form').ajaxForm({ 
    	dataType:	'json',
    	beforeSubmit: function(formData, form, options) {
    		if ($.data(form, 'submitted')) return false;
	
	        var freq = 1000; // freqency of update in ms
	        var uuid = gen_uuid(); // id for this upload so we can fetch progress info.
	        var progress_url = '/upload-progress/'; // ajax view serving progress info
	
	        // Append X-Progress-ID uuid to form data
	        formData.push({ "name": "X-Progress-ID", "value": uuid });
	        
	        $('#upload-school-country-assignments-progress').progressbar({ value: 0 });
	        
	        // Update progress bar
	        function update_progress_info() {
	            $.getJSON(progress_url, {'X-Progress-ID': uuid}, function(data, status){
	                if (data) {
	                    var progressPercent = parseInt(100*parseInt(data.uploaded) / parseInt(data.length));
	        	        $("#upload-school-country-assignments-progress").progressbar("option", "value", progressPercent);

	                    if(progressPercent < 100)
	                    	progressTimer = window.setTimeout(update_progress_info, freq);
	                }
	            });
	        };
	        progressTimer = window.setTimeout(update_progress_info, freq);
	
	        $.data(form, 'submitted', true); // mark form as submitted.
	        return true;
    	},
        success:   function(return_data) {
    		window.clearTimeout(progressTimer);
    		$('#upload-school-country-assignments-progress').progressbar("destroy");
    		$('div#upload-school-country-assignments-form .ui-state-error').remove();
			if(return_data != null) {
				if(return_data.errors != null) {
		  			// show errors
					output = "<div style=\"padding: 0pt 0.7em;\" class=\"ui-state-error ui-corner-all\"> <p><span style=\"float: left; margin-right: 0.3em;\" class=\"ui-icon ui-icon-alert\"></span> ";
					for(i = 0; i < return_data.errors.length; i++) {
						output += return_data.errors[i] + "<br/>";
					}
					output += "</p></div>";
					
					$('div#upload-school-country-assignments-form').append(output);
				}
				if(return_data.table != null) {
					// refresh the delegate positions table
					//return_data.table = $("<div/>").html(return_data.table).text();
					get_school_country_assignments_callback(return_data, schoolSelectSource, '#countries-to-schools-form-dialog');
				}
			}
		}
    });

});

{% endblock %}

{% block pagecontent %}
<div class="header">
<h1>{{ object.name }} Registration</h1>
<h3>Secretariat Access</h3>
</div>

<div class="secretariat-content">
<div id="tabs">
	<ul class="tab-link">
		<li><a href="#settings"><img class="tab-link" src="{{MEDIA_URL}}/icons/kcmsystem.png" /><br/>Settings</a></li> 
		<li><a href="#stats"><img class="tab-link" src="{{MEDIA_URL}}/icons/kpercentage.png" /><br/>Statistics</a></li>
		<li><a href="#spreadsheets"><img class="tab-link" src="{{MEDIA_URL}}/icons/kchart.png" /><br/>Spreadsheets</a></li>
		<li><a href="#schools"><img class="tab-link" src="{{MEDIA_URL}}/icons/kdmconfig.png" /><br/>Schools</a></li>
		<li><a href="#fees"><img class="tab-link" src="{{MEDIA_URL}}/icons/emblems-money.png" /><br/>Fees</a></li>
		<!-- <li><a href="#store"><img class="tab-link" src="{{MEDIA_URL}}/icons/shopping_trolley.png" /><br/>Store</a></li> -->
	</ul>
	
	<div id="settings" class="secretariat-pane" >
		<p><a href="#" id="basic-conference-form-dialog-link">Basic Conference Information</a></p>
		<div id="basic-conference-form-dialog" title="Basic Conference Information"></div>
		
		<p><a href="#" id="countries-form-dialog-link">Countries</a></p>
		<div id="countries-form-dialog" title="Conference Countries"></div>
		
		<p><a href="#" id="committees-form-dialog-link">Committees</a></p>
		<div id="committees-form-dialog" title="Conference Committees"></div>
		
		<p><a href="#" id="committees-to-countries-form-dialog-link">Assign Committees to Countries</a></p>
		<div id="committees-to-countries-form-dialog" title="Assign committees to countries">
			<div id="upload-delegate-positions-form">
				<p>Import a spreadsheet containing the country-committee assignments.  The formatting must be the same as the downloaded spreadsheet (available <a href="downloads/?country-committee-assignments">here</a>). Only CSV files are accepted.</p>
				<form enctype="multipart/form-data" action="ajax/upload-delegate-positions" method="post" id="upload-delegate-positions-form">{% csrf_token %}
					<label for="id_file">Upload:</label> <input type="file" name="file" id="id_file" accept="text/csv" />
				<input type="submit" class="button" value="Submit" />
				</form>
				<div id="upload-delegate-positions-progress" class="upload-progress"></div>
			</div>
			<div id="positions-assignment-table"></div>
		</div>
		
		<p><a href="#" id="countries-to-schools-form-dialog-link">Assign Countries to Schools</a></p>
		<div id="countries-to-schools-form-dialog" title="Assign countries to schools">
			<div id="upload-school-country-assignments-form">
				<p>Import a spreadsheet containing the country-school assignments.  The formatting must be the same as the downloaded spreadsheet (available <a href="downloads/?school-country-assignments">here</a>). Only CSV files are accepted.</p>
				<form enctype="multipart/form-data" action="ajax/upload-school-country-assignments" method="post" id="upload-school-country-assignments-form">{% csrf_token %}
					<label for="id_file">Upload:</label> <input type="file" name="file" id="id_file" accept="text/csv" />
				<input type="submit" class="button" value="Submit" />
				</form>
				<div id="upload-school-country-assignments-progress" class="upload-progress"></div>
			</div>
			<div id="school-country-assignment-table"></div>
		</div>
		
		<p><a href="#" id="edit-delegate-positions-form-dialog-link">Edit Delegate Positions</a></p>
		<div id="edit-delegate-positions-form-dialog" title="Edit Delegate Positions">
			<div id="delegate-positions-table"></div>
		</div>
	</div>	

	<div id="stats" class="secretariat-pane" >
		
		<table style="margin: 0 auto;">
			<tr><td style="text-align:left; padding: 5px;" colspan="2"><b>Schools</b></td></tr>
			<tr><td style="text-align:left; padding: 5px;">Schools with an account: </td><td style="text-align:right; padding: 5px;">{{ object.school_set.count }}</td></tr>
			<tr><td style="text-align:left; padding: 5px;">Schools with assigned countries: </td><td style="text-align:right; padding: 5px;">{{ object.schools_assigned_countries_count }}</td></tr>
			<tr><td style="text-align:left; padding: 5px;">Schools with country preferences: </td><td style="text-align:right; padding: 5px;">{{ object.country_preference_count }}</td></tr>
			<tr><td style="text-align:left; padding: 5px;">Schools with delegate count request: </td><td style="text-align:right; padding: 5px;">{{ object.delegate_count_preference_count }}</td></tr>

			<tr><td style="text-align:left; padding: 5px; padding-top:15px" colspan="2"><b>Delegates</b></td></tr>
			<tr><td style="text-align:left; padding: 5px;">Delegate positions requested: </td><td style="text-align:right; padding: 5px;">{{ object.delegate_count_preference_total }}</td></tr>
			<tr><td style="text-align:left; padding: 5px;">Countries assigned to schools: </td><td style="text-align:right; padding: 5px;">{{ object.assigned_countries_count }}</td></tr>
			<tr><td style="text-align:left; padding: 5px;">Delegate positions assigned to schools: </td><td style="text-align:right; padding: 5px;">{{ object.assigned_positions_count }}</td></tr>
			<tr><td style="text-align:left; padding: 5px;">Unassigned delegate positions: </td><td style="text-align:right; padding: 5px;">{{ object.unassigned_delegate_position_count }}</td></tr>
			<tr><td style="text-align:left; padding: 5px;">Registered delegates: </td><td style="text-align:right; padding: 5px;">{{ object.delegates_count }}</td></tr>
		</table>
		
		<img style="padding: 20px; margin: 0 auto;" src="{{ object.delegate_registration_by_month_graph }}" alt="" />
		
		<img style="padding: 20px; margin: 0 auto;" src="{{ object.delegate_preference_by_month_graph }}" alt="" />
		
		<img style="padding: 20px; margin: 0 auto;" src="{{ object.delegate_preference_modified_by_month_graph }}" alt="" />
		
		<img style="padding: 20px; margin: 0 auto;" src="{{ object.payments_by_month_graph }}" alt="" />

		<img style="padding: 20px; margin: 0 auto;" src="{{ object.school_accounts_by_month_graph }}" alt="" />
		
	</div>

	<div id="spreadsheets" class="secretariat-pane" >
		<a href="downloads/?sponsor-contacts">Sponsor Contact Info Spreadsheet</a><br/>
		<a href="downloads/?delegates">Delegates Spreadsheet</a><br/>
		<br/>
		<a href="downloads/?school-country-assignments">School-Country Assignments</a><br/>
		<a href="downloads/?country-committee-assignments">Country-Committee Assignments</a><br/>
		<br/>
		<a href="downloads/?country-preferences">Country Preferences</a><br/>
		<a href="downloads/?delegate-count-requests">Delegate Count Requests</a><br/>
	</div>

	<div id="schools" class="secretariat-pane" >
		Search:
			<form method="post" action="see-school" class="search-schools">{% csrf_token %}
				<input id="id_name" name="name"/>
				<input type="submit" class="button" name="submitschool" value="Go">
			</form>
		
		Select from list:
			<form method="post" action="see-school">{% csrf_token %}
				<select id="id_name" name="name">
					{% for school in object.school_set.all %}
						<option value="{{ school.name }}">{{ school.name }}</option>
					{% endfor %}
				</select>
				<input type="submit" class="button" name="submitschool" value="Go">
			</form>
	</div>

	<div id="fees" class="secretariat-pane" >
		<table style="margin: 0 auto;">
			{% load currencyformat %}
			<tr><td style="text-align:left; padding: 5px;">Total Fees: </td><td style="text-align:right; padding: 5px;">{{ object.feestructure.total_fee|currencyformat }}</td></tr>
			<tr><td style="text-align:left; padding: 5px;">Total Paid: </td><td style="text-align:right; padding: 5px;">{{ object.feestructure.total_payments|currencyformat }}</td></tr>
			<tr><td style="text-align:left; padding: 5px;">Total Balance Due: </td><td style="text-align:right; padding: 5px;">{{ object.feestructure.balance_due|currencyformat }}</td></tr>
		</table>
		<p>Fees totaled above only include schools with registered delegates.</p> 
		
		<p><a href="#" id="payments-form-dialog-link">Payments</a></p>
		<div id="payments-form-dialog" title="Conference Fee Payments"></div>
		
		<h3 style="font-size: 100%;">Fee Structure:</h3>
		<p><a href="#" id="fee-form-dialog-link">Basic Fees</a></p>
		<div id="fee-form-dialog" title="Conference Fee Structure"></div>

		<p><a href="#" id="datepenalty-form-dialog-link">Date-Based Penalties and Discounts</a></p>
		<div id="datepenalty-form-dialog" title="Conference Date-Based Penalties"></div>

		<h3 style="font-size: 100%;">Download All Invoices:</h3>
		<table class="center">
			<tr>
				<td class="center" style="padding-right: 30px">
					<a href="invoices"><img class="tab-link" src="{{MEDIA_URL}}/icons/pdf.png"/></a><br/>
					<a href="invoices">Download PDF</a> (Slow)
				</td>
				<td class="center">
					<a href="invoices-doc"><img class="tab-link" src="{{MEDIA_URL}}/icons/doc.png"/></a><br/>
					<a href="invoices-doc">Download Word Doc</a>
				</td>
			</tr>
		</table>
	</div>

	<!--<div id="store" class="secretariat-pane" >
		Coming Soon!
	</div>-->

</div>
</div>
{% endblock %}
